#ifndef __M_SINK_H__
#define __M_SINK_H__

#include "util.hpp"
#include <memory>
#include <iostream>
#include <fstream>
#include <cassert>
#include <sstream>
#include <string>

namespace Mylog
{
    class LogSink
    {
    public:
        using ptr = std::shared_ptr<LogSink>;
        virtual ~LogSink() {};
        virtual void log(const char *data, size_t len) = 0;
    };

    class StdoutSink : public LogSink
    {
    public:
        void log(const char *data, size_t len) override
        {
            std::cout.write(data, len);
        }
    };

    // 将日志落地到指定文件
    // 如果写日志时都打开文件会导致效率降低，所以构造时直接打开文件，并将操作句柄管理起来
    class FileSink : public LogSink
    {
    public:
        FileSink(const std::string pathname)
            : _pathname(pathname)
        {
            // 1. 创建文件路径
            Mylog::util::File::createDirectory(Mylog::util::File::path(pathname));
            // 2. 打开文件
            _ofs.open(pathname, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        void log(const char *data, size_t len) override
        {
            _ofs.write(data, len);
            assert(_ofs.good());
        }

    private:
        std::string _pathname;
        std::ofstream _ofs;
    };

    // 滚动文件（文件大小进行滚动 ）
    class RollBySizeSink : public LogSink
    {
    public:
        RollBySizeSink(const std::string basename, size_t maxsize)
            : _basename(basename), _maxsize(maxsize), _cursize(0), _name_count(0)
        {
            // 1. 获取文件名（basename + 时间）
            std::string filename = createNewFilename();
            // 2. 创建文件目录
            Mylog::util::File::createDirectory(Mylog::util::File::path(filename));
            // 3. 创建并打开文件
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        void log(const char *data, size_t len) override
        {
            if (_cursize > _maxsize)
            {
                _ofs.close();
                std::string filename = createNewFilename();
                _ofs.open(filename, std::ios::binary | std::ios::app);
                assert(_ofs.is_open());
                _cursize = 0;
            }
            _ofs.write(data, len);
            _cursize += len;
            assert(_ofs.good());
        }

    private:
        // 进行大小判断，超出指定大小则创建新文件
        std::string createNewFilename()
        {
            // 获取当前时间，以时间来构造文件扩展名
            time_t t = Mylog::util::Date::now();
            struct tm lt;
            localtime_r(&t, &lt);
            std::stringstream ss;
            ss << _basename;
            ss << lt.tm_year + 1900;
            ss << lt.tm_mon + 1;
            ss << lt.tm_mday;
            ss << lt.tm_hour;
            ss << lt.tm_min;
            ss << lt.tm_sec;
            ss << "-";
            ss << _name_count++;
            ss << ".log";
            return ss.str();
        }

    private:
        size_t _name_count;
        std::string _basename;
        std::ofstream _ofs;
        size_t _maxsize;
        size_t _cursize;
    };

    // 工厂模式
    class SinkFactory
    {
    public:
        template <class SinkType, class... Args>
        static LogSink::ptr create(Args &&...args)
        {
            return std::make_shared<SinkType>(std::forward<Args>(args)...);
        }
    };
}

#endif
